package com.course.business.controller.web.discusspost;

import com.alibaba.fastjson.JSONObject;
import com.course.server.domain.Member;
import com.course.server.domain.discusspost.Message;
import com.course.server.dto.MemberDto;
import com.course.server.dto.PageDto;
import com.course.server.dto.ResponseDto;
import com.course.server.service.MemberService;
import com.course.server.service.discusspost.MessageService;
import com.course.server.util.CommunityConstant;
import com.course.server.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/web")
public class MessageController implements CommunityConstant {

    @Autowired
    private MessageService messageService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private MemberService memberService;

    // 私信列表
    @RequestMapping(path = "/letter/list")
    public ResponseDto getLetterList(@RequestBody PageDto pageDto) {

        ResponseDto responseDto = new ResponseDto();
        messageService.findConversations(pageDto);
        responseDto.setContent(pageDto);
        return responseDto;
//        return "/site/letter";
    }

    @RequestMapping(path = "/letter/detail/{conversationId}")
    public ResponseDto getLetterDetail(@PathVariable("conversationId") String conversationId, @RequestBody PageDto pageDto) {

        // 私信列表
        ResponseDto responseDto = new ResponseDto();
        messageService.findLetters(conversationId,pageDto);
        responseDto.setContent(pageDto);
        return responseDto;
//        return "/site/letter-detail";
    }

/*    //这两个方法放到MessageService去了

    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if (hostHolder.getUser().getId() == id0) {
            return userService.findUserById(id1);
        } else {
            return userService.findUserById(id0);
        }
    }

    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                if (hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }
*/
    @RequestMapping(path = "/letter/send", method = RequestMethod.POST)
    public ResponseDto sendLetter(@RequestBody Map<String,String> map) {
        String toName=map.get("toName");
        String content=map.get("content");

        MemberDto target = memberService.findByMobile(toName);
        if (target == null) {
            return new ResponseDto(false, "目标用户不存在!");
        }

        Message message = new Message();
        message.setFromId(hostHolder.getMember().getId());
        message.setToId(target.getId());
        if (message.getFromId().compareTo(message.getToId())<0 ) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setCreateTime(new Date());
        messageService.addMessage(message);

        return new ResponseDto();
    }

    // 删除私信和通知
    @RequestMapping(path = "/letter/delete", method = RequestMethod.POST)
    public ResponseDto deleteLetter(String id) {
        messageService.deleteMessage(id);
        return new ResponseDto();
    }

    @RequestMapping(path = "/notice/list", method = RequestMethod.GET)
    public ResponseDto getNoticeList() {
        Map<String,Object> dto=new HashMap<>();
        Member member = hostHolder.getMember();
        String userId;
        if(member !=null){
            userId= member.getId();
        }else{
            return new ResponseDto(false,"用户未登录!");
        }

        // 查询评论类通知
        Message message = messageService.findLatestNotice(userId, TOPIC_COMMENT);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            /*
            EventConsumer类里，是用HashMap转的。
            message.setContent(JSONObject.toJSONString(content));//Map<String, Object> content
            所以也要转回Map：JSONObject.parseObject(content, HashMap.class);
             */
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", memberService.findUserById((String)data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(userId, TOPIC_COMMENT);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(userId, TOPIC_COMMENT);
            messageVO.put("unread", unread);

            dto.put("commentNotice", messageVO);
        }

        // 查询点赞类通知
        message = messageService.findLatestNotice(userId, TOPIC_LIKE);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", memberService.findUserById((String) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(userId, TOPIC_LIKE);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(userId, TOPIC_LIKE);
            messageVO.put("unread", unread);

            dto.put("likeNotice", messageVO);
        }

        // 查询关注类通知
        message = messageService.findLatestNotice(userId, TOPIC_FOLLOW);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", memberService.findUserById((String) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));

            int count = messageService.findNoticeCount(userId, TOPIC_FOLLOW);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(userId, TOPIC_FOLLOW);
            messageVO.put("unread", unread);

            dto.put("followNotice", messageVO);
        }

        // 查询未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(userId, null);
        dto.put("letterUnreadCount", letterUnreadCount);
        int noticeUnreadCount = messageService.findNoticeUnreadCount(userId, null);
        dto.put("noticeUnreadCount", noticeUnreadCount);

        ResponseDto responseDto=new ResponseDto();
        responseDto.setContent(dto);
        return responseDto;
//        return "/site/notice";
    }

    @RequestMapping(path = "/notice/detail/{topic}")
    public ResponseDto getNoticeDetail(@PathVariable("topic") String topic,@RequestBody PageDto pageDto) {

        ResponseDto responseDto = new ResponseDto();
        messageService.findNotices( topic,pageDto);
        responseDto.setContent(pageDto);
        return responseDto;

//        return "/site/notice-detail";
    }

    @RequestMapping(path = "/message/unreadcount/{userId}", method = RequestMethod.POST)
    public ResponseDto getMessageUnreadcount(@PathVariable("userId") String userId) {
        ResponseDto responseDto = new ResponseDto();
        Member user = memberService.findUserById(userId);
        if (user != null) {
            int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
            int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
            responseDto.setContent(letterUnreadCount + noticeUnreadCount);
        }
        return responseDto;
    }

}
